package com.gao.transportapi.aspect.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gao.transportapi.common.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import org.springframework.web.servlet.HandlerInterceptor;



@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户信息
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || authHeader.isEmpty()) {
            response.setStatus(401);
            return false;
        }

        // 分割Bearer和Token
        String[] parts = authHeader.split(" ");
        if (parts.length != 2 || !parts[0].equals("Bearer")) {
            log.error("认证格式无效: {}", authHeader);
            response.setStatus(401);
            return false;
        }

        String token = parts[1];
        // 2.判断是否为空
        if (StringUtils.isNotBlank(token)) {
            // 不为空，保存到ThreadLocal
            if(token.equals("sk-shuai2418jgao31yehuj4dev41hejkd"))return true;

            response.setStatus(401);
            return false;
        }
        else {
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserContext.removeUser();
    }


}
